package lesson.c4;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.io.FileReader;
import java.io.FileWriter;

public class DataStore {
	private static volatile DataStore _INSTANCE = null;
	
	private HashMap<String, String> _map = new HashMap<String, String>();
	
	private static String FILE_PATH = "./data/store.txt";
	
	private DataStore() {
		File fi = new File(DataStore.FILE_PATH);
		if(fi.exists()){
			try {
				FileReader reader = new FileReader(fi);
				BufferedReader bReader = new BufferedReader(reader);
				String tmp = "";
				while((tmp = bReader.readLine())!=null) {
		            String[] tAry = tmp.trim().split("\t");
		            if(tAry.length != 2){
		            	continue;
		            }
		            _map.put(tAry[0], tAry[1]);
		        }
				bReader.close();
			}catch(IOException e){
				e.printStackTrace();
			}
		}
	}
	
	public static DataStore getInstance() {
		if (_INSTANCE == null){
			synchronized (DataStore.class){
				if(_INSTANCE == null){
					_INSTANCE = new DataStore();
				}
			}
		}
		return _INSTANCE;
	}
	
	public String get(String key){
		return _map.get(key);
	}
	
	public void set(String key, String value){
		if(_map.containsKey(key)){
			_map.put(key, value);
			saveAll();
		}else{
			_map.put(key, value);
			save(key, value);
		}
	}
	
	public void reset(){
		_map.clear();
		saveAll();
	}
	
	private void saveAll(){
		Iterator<Entry<String, String>> iter = _map.entrySet().iterator();
		File fi = new File(DataStore.FILE_PATH);
		try {
			FileWriter writer = new FileWriter(fi, false);
			BufferedWriter bWriter = new BufferedWriter(writer);
			while(iter.hasNext()){
				Entry<String, String> entry = iter.next();
				bWriter.append(entry.getKey() + "\t" + entry.getValue() + "\n");
			}
			bWriter.flush();
			bWriter.close();
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	
	private void save(String key, String value){
		File fi = new File(DataStore.FILE_PATH);
		boolean append = false;
		try {
			if(fi.exists()) append = true;
			FileWriter writer = new FileWriter(fi, append);
			BufferedWriter bWriter = new BufferedWriter(writer);
			bWriter.append(key + "\t" + value + "\n");
			bWriter.flush();
			bWriter.close();
		}catch(IOException e){
			e.printStackTrace();
		}
	}
}
